Page({
    data: {
        currentTab: 0, // 0-当前借阅，1-历史借阅
        currentBorrows: [], // 当前借阅数据
        historyBorrows: [], // 历史借阅数据
        branchList: [], // 书房列表数据
        selectedRecordId: null // 当前操作的借阅记录ID

    },

    // 点击选项卡切换
    switchTab(e) {
        const tab = parseInt(e.currentTarget.dataset.tab);
        this.setData({
            currentTab: tab
        });
    },

    // 滑动切换监听
    swiperChange(e) {
        const currentTab = e.detail.current;
        this.setData({
            currentTab
        });
    },

    // 初始化数据（示例）
    onLoad() {
        this.borrowed();
        // 加载书房列表
        this.loadBranchList();
    },

    formatTime(timestamp) {
        if (!timestamp) return '未指定';
        const date = new Date(timestamp);
        return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`;
    },

    // 续借操作
    onRenew(e) {
        const recordId = e.currentTarget.dataset.recordid;
        const that = this;

        wx.showLoading({
            title: '处理中...'
        });

        wx.request({
            url: `http://localhost:8080/borrowRecord/renew/${recordId}`,
            method: 'PUT',
            success: (res) => {
                wx.showToast({
                    title: '续借成功',
                    icon: 'success'
                });
                this.onLoad();

            },
            fail: (error) => {
                wx.showToast({
                    title: '网络连接失败',
                    icon: 'none'
                });
            },
            complete: () => {
                wx.hideLoading();
            }
        });
    },

    //获取借阅记录
    borrowed() {
        wx.request({
            url: 'http://localhost:8080/borrowRecord/queryByUserId?userId=' + wx.getStorageSync('userId'),
            method: 'GET',
            success: (res) => {
                if (res.statusCode === 200 && res.data.code === 0) {
                    const formattedData = res.data.data.map(item => ({
                        ...item,
                        borrowTime: this.formatTime(item.borrowTime),
                        dueTime: this.formatTime(item.dueTime),
                        returnTime: this.formatTime(item.returnTime)
                    }));
                    // 根据状态分类数据
                    const {
                        current,
                        history
                    } = formattedData.reduce((acc, item) => {
                        if (item.status === "在借") {
                            acc.current.push(item);
                        } else {
                            acc.history.push(item);
                        }
                        return acc;
                    }, {
                        current: [],
                        history: []
                    });

                    // 更新页面数据
                    this.setData({
                        currentBorrows: current,
                        historyBorrows: history
                    });
                    //   this.setData({ currentBorrows: formattedData });
                } else {
                    // 处理错误响应
                    wx.showToast({
                        title: res.data.msg || '加载失败',
                        icon: 'none'
                    });
                }
            }
        })
    },

    loadBranchList() {
        wx.request({
            url: 'http://localhost:8080/branch/list2',
            method: 'GET',
            success: (res) => {
                this.setData({
                    branchList: res.data.data
                });
            }
        });
    },

    // 触发选择器（保持按钮样式）
    triggerPicker(e) {
        // 保存当前记录ID到临时变量
        const recordId = e.currentTarget.dataset.recordid;
        // console.log(recordId)
        this.setData({
            selectedRecordId: recordId
        });
    },

    onBranchSelect(e) {
        const branchIndex = e.detail.value;
        console.log("recordId,branchId:")
        console.log(this.data.selectedRecordId)
        const recordId = this.data.selectedRecordId;
        console.log(this.data.branchList[branchIndex].branchId)
        const branchId = this.data.branchList[branchIndex].branchId;

        if (!branchId || !recordId) return;

        wx.showLoading({
            title: '还书中...'
        });

       
        wx.request({ 
            url: 'http://localhost:8080/borrowRecord/return?recordId=' + recordId + '&branchId=' + branchId,
            method: 'PUT',
            success: (res) => {
                // 更新前端数据
                const updatedCurrent = this.data.currentBorrows.filter(
                    item => item.recordId !== recordId
                );
                const newHistory = this.data.historyBorrows.concat(
                    this.data.currentBorrows.find(item => item.recordId === recordId)
                );

                this.setData({
                    currentBorrows: updatedCurrent,
                    historyBorrows: newHistory
                });

                wx.showToast({
                    title: '还书成功',
                    icon: 'success'
                });

            },
            complete: () => wx.hideLoading()
        });
    }

});